package com.dobby.htmlunit.demo.yidian;

import com.alibaba.fastjson.JSONObject;
import com.gargoylesoftware.htmlunit.*;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jonas on 2017/2/24.
 */
public class YidianPoster {


    private static WebClient webClient = null;

    private String cookie = null;

    public YidianPoster() {
    }

    private YidianPoster(String cookie) {
        this.cookie = cookie;
    }

    private static WebClient getWebClient() {
        if(webClient == null) {
            webClient = new WebClient();
            webClient.getOptions().setCssEnabled(false);
            webClient.getOptions().setJavaScriptEnabled(true);
            webClient.getOptions().setRedirectEnabled(true);
            webClient.setAjaxController(new NicelyResynchronizingAjaxController());
            webClient.getCookieManager().setCookiesEnabled(true);
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            webClient.waitForBackgroundJavaScript(10000);
            webClient.getOptions().setTimeout(10000);
        }
        return webClient;
    }

    public static YidianPoster addCookie(String cookie) {
        if(StringUtils.isNotBlank(cookie)) {
            return new YidianPoster(cookie);
        }
        return new YidianPoster();
    }

    private WebRequest addHeaders(WebRequest request) throws Exception {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("accept","application/json, text/javascript, */*; q=0.01");
        headers.put("accept-language","zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4");
        headers.put("content-type","application/json; charset=utf-8");
        headers.put("origin","http://mp.yidianzixun.com");
        headers.put("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
        headers.put("x-requested-with","XMLHttpRequest");
        if(null != this.cookie) {
            headers.put("cookie", this.cookie);
        } else {
            throw new Exception("缺少cookie信息");
        }
        request.setAdditionalHeaders(headers);
        return request;
    }


    public String getInfo() throws Exception {
        String url = "http://mp.yidianzixun.com/model/Article?page=1&status=2,7&has_data=1&type=original&title=&page_size=" + Integer.MAX_VALUE;
        WebRequest request = new WebRequest(new URL(url), HttpMethod.GET);
        request.setCharset("UTF-8");
        addHeaders(request);

        Page page = getWebClient().getPage(request);
        WebResponse webResponse = page.getWebResponse();
        String jsonInfo = webResponse.getContentAsString();
        System.out.println(jsonInfo);
        return null;
    }



}
